const MUTATION_TYPES = {
  VALUES: "VALUES"
};

const state = {
  groups: {},
  values: {}
};
const getters = {};

const mutations = {
  [MUTATION_TYPES.VALUES](state, dictionaries) {
    state.groups = dictionaries;
    state.values = {};
    Object.values(dictionaries)
      .flat()
      .forEach((dictionary) => {
        let key = dictionary.group + "-" + dictionary.value;
        state.values[key] = { ...dictionary, label: dictionary.name };
      });
  }
};

const actions = {
  async loadAll({ commit, dispatch }) {
    let dictionaries = await dispatch(
      "basic/loadDictionaries",
      {},
      { root: true }
    );
    commit(MUTATION_TYPES.VALUES, dictionaries);
  }
};

class ValueReader {
  constructor(group) {
    this.group = group;
    return new Proxy(this, {
      get(target, name) {
        if (name === "valueList") {
          return state.groups[target.group];
        } else {
          let key = target.group + "-" + name;
          return state.values[key];
        }
      }
    });
  }
  values() {
    return this.valueList || [];
  }
}

export default {
  namespaced: true,
  state,
  getters,
  mutations,
  actions
};

export { ValueReader };
